package phase03.module04.dao;


import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Alex Zhang
 */
public class HelloDao {
    private DataSource ds;

    public void createUser(String username, String password, String email) {
        ds = DbPool.getDataSource();
        try {
            Connection connection = ds.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement("insert into user values(?, ?, ?)");
            preparedStatement.setString(1, username);
            preparedStatement.setString(2, password);
            preparedStatement.setString(3, email);
            preparedStatement.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public List<Map<String, Object>> getUsers() {
        ds = DbPool.getDataSource();
        List<Map<String, Object>> rs = new ArrayList<>();
        try {
            QueryRunner run = new QueryRunner(ds);
            rs = run.query("select * from user", new MapListHandler());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }
}
